package MTT::Libs::AlarmRun;

use Moose;

use utf8;

our %SIG;

use Encode qw(encode decode);
use Email::Send;
use MIME::Lite;
use Time::HiRes qw(gettimeofday tv_interval);
use POSIX qw(strftime);
use IO::File;

use MTT::Libs::Masks;
use MTT::Schema;
use MTT::Libs::Alarm;

use Data::Dumper;

has 'log' => ( is => 'ro' );
has alarm_log => ( is => 'ro' ); 

has schema_mtt => ( is => 'rw' );
has schema_stat => ( is => 'rw' );
has schema_call => ( is => 'rw' );

has alarm_script => ( is => 'rw' );

has start_time => ( is => 'rw', default => sub { strftime('%Y-%m-%d %H:%M:%S', localtime) } );
has masks => ( is => 'rw' );
has host => ( is => 'rw' );
has ctx => ( is => 'rw' );

sub BUILD {
	my ($self, $args) = @_;

	if ( $self->ctx && !$self->schema_call ) {
		my $ci = $self->ctx->config->{CallDB}->{connect_info};
		my $dbh = DBI->connect(
			$ci->{dsn},
			$ci->{user},
			$ci->{password}
		) || die DBI->errstr;
		$dbh->do( $ci->{on_connect_do} );

		$self->schema_call( $dbh );
		$self->schema_call->{mysql_enable_utf8} = 1;
	}

	if ( $self->ctx && !$self->schema_stat ) {
		my $ci = $self->ctx->config->{StatDB}->{connect_info};
		my $dbh = DBI->connect(
			$ci->{dsn},
			$ci->{user},
			$ci->{password}
		) || die DBI->errstr;
		$dbh->do( $ci->{on_connect_do} );

		$self->schema_stat( $dbh );
		$self->schema_stat->{mysql_enable_utf8} = 1;
	}

	unless ( $self->masks ) {
		$self->masks( MTT::Libs::Masks->new(dbh => $self->schema_mtt->storage->dbh) );
	}

}

sub run {
	my ($self, $a) = @_;

	my @alarms;
	if ( ref $a ) {
		push @alarms, $a;
	}
	else {
		my $aids = $self->schema_mtt->storage->dbh_do(
			sub {
				my ($storage, $dbh, $start_time) = @_;

				return $dbh->selectall_arrayref(
					'SELECT id FROM alarms WHERE status = 1 AND date_run <= ? AND state = 0',
					undef,
					$self->start_time
				);
			});

		foreach ( @$aids ) {
			my $alarm = MTT::Libs::Alarm->new(schema => $self->schema_mtt);
			$alarm->load( $_->[0] );
			$alarm->running(1);
			push @alarms, $alarm;
		}
	}

	$SIG{CHLD} = sub { print "child exit" };

	foreach my $alarm ( @alarms ) {

		if ( 0 == fork() ) {

			if ( $alarm->alarm_type eq 'ring' ) {
				$alarm->run_check( $self->schema_call->clone() );

			}
			else {
				$self->create_temp_table($alarm);
				$alarm->run_check( $self->schema_stat->clone() );
			}

			if ( $alarm->alarmed ) {
				$self->send_mail($alarm);
			}

			$alarm->set_nexttime();
			$alarm->running(0);

			$self->drop_temp_table($alarm);
			exit(0);
		}
	}
	while ( wait > 0 ) {};
}

=pod
my $first_datetime = shift; #Format -  2010-12-24 12:00:00
    my $interval = shift; # 15,60,90,120 i T.D.
    my $alarm_name = shift; # table name for alarm
    my $type_alarm = shift; # trunk,mask,short_mask

    my $switch = shift; # switch name
    my $parameter = shift; # trunk name, mask, short_mask
    my $second_datetime = shift; # count days  FOR PREV week,or another day
    my $count_attempts = shift; # for A alarm (for ASR, NER)
    my $count_answered = shift; # for A alarm (for ACD)
=cut

sub create_temp_table {
	my ($self, $alarm) = @_;

	my $table_name = 'alarm_' . $alarm->id;

	my $type_report = $alarm->props->{type_alarm} || 'ASR';
	
	my $interval = $alarm->interval();
	my $alarm_type = $alarm->alarm_type();
	my $switches = join(',', map { "'$_'" } $alarm->get_switch_names());

	my $parameter;
	my ($trunks, $codes) = ('', '');
	if ( $alarm_type eq 'trunk') {
		$trunks = join(',', map { "'" . $_ . "'" } split(/,/, $alarm->props->{trunks}))
			if $alarm->props->{trunks};
		$parameter = join(',', map { "'" . $_ . "'" } split(/,/, $alarm->props->{trunks}))
			if $alarm->props->{trunks};
	}
	elsif ( $alarm_type eq 'mask' ) {
		my $amask = $self->masks->get_mask( $alarm->props->{amask} ) if $alarm->props->{amask}; 
		my $bmask = $self->masks->get_mask( $alarm->props->{bmask} ) if $alarm->props->{bmask}; 
#		$amask = $alarm->props->{amask}; 
#		$bmask = $alarm->props->{bmask}; 
		$parameter = join(',', grep { $_ =~ /\w/ } map { "'" . ($_ || '') . "'" } ( $amask, $bmask ) );
		$codes = join(',', grep { $_ =~ /\w/ } map { "'" . ($_ || '') . "'" } ( $amask, $bmask ) );
	}
	elsif ( $alarm_type eq 'short' ) {
		my ($amask, $p) = $self->masks->get_mask( $alarm->props->{amask} ) if $alarm->props->{amask}; 
		if ($amask) {
			$amask = $p->[10];
		}
		my ($bmask, $p2) = $self->masks->get_mask( $alarm->props->{bmask} ) if $alarm->props->{bmask}; 
		if ($amask) {
			$bmask = $p->[10];
		}

		$parameter = join(',',  grep { $_ =~ /\w/ } map { "'" . $_ || '' . "'" } ( $amask, $bmask ));
		$codes = join(',',  grep { $_ =~ /\w/ } map { "'" . $_ || '' . "'" } ( $amask, $bmask ));

	}

	
	my $prev = $alarm->props->{interval_prev} || 7;
	my $count_attempts = $alarm->props->{mincall_asr} || 100;
	my $count_answered = $alarm->props->{mincall_acd} || 30;

	my $type_number = $alarm->props->{type_number} || '';
	$type_number = '' if $type_number eq 'all';

	my $start_time = strftime('%Y-%m-%d %H:%M:%S', localtime);

#	$alarm->running(0);
#	exit;

#	warn "----- 13 ----- Parameters ----- >>>\n" 
#		. join("\n", ($type_report, $table_name, $interval, $alarm_type, $switches, $parameter, $prev,
#						$count_attempts, $count_answered));


#	
#	Stat->call_create_temp_tables_for_alarm
#
	eval {
#		system('perl ' . $self->alarm_script . " \"$type_report\" \"$start_time\" \"$interval\" \"$table_name\" \"$alarm_type\" \"$switches\" \"$parameter\" \"$prev\" \"$count_attempts\" \"$count_answered\"");
#		print('perl ' . $self->alarm_script . " \"$type_report\" \"$start_time\" \"$interval\" \"$table_name\" \"$alarm_type\" \"$switches\" \"$trunks\" \"$codes\" \"$prev\" \"$count_attempts\" \"$count_answered\" \"$type_number\"");
#	$alarm->running(0);
#	exit;

		system('perl ' . $self->alarm_script . " \"$type_report\" \"$start_time\" \"$interval\" \"$table_name\" \"$alarm_type\" \"$switches\" \"$trunks\" \"$codes\" \"$prev\" \"$count_attempts\" \"$count_answered\" \"$type_number\"");
	};
	die $@ if $@;

	$alarm->source_table( $table_name );
	$alarm->source_table_prev( $table_name . '_prev' );
}


sub drop_temp_table {
	my ($self, $alarm) = @_;

}

sub send_mail {
	my ($self, $alarm) = @_;

	my $message;
	$message .= '<html>';
	$message .= <<'__STYLE__';
	<head>
	<meta http-equiv="content-type" content="text/html; charset=utf-8">
	<style> 
		.header {
			background: #a5a5a5;
			font-size: 1.3em;
			foreground: #131313;
		}

		.first_a {
			background: #d7d7d7;
		} 
		.second_a {
			background: #a7a7a7;
		}
	</style>
	</head>
	<body>
__STYLE__

	$message .= '<span>Название: ' . $alarm->name . '</span><br/><br/>';
	$message .= '<p>Время обработки: ' . strftime('%Y-%m-%d %H:%M:%S', localtime) . '</span><br/>';
	$message .= '<pre>' . $alarm->message . '</pre>' if $alarm->message;

	my $result = $alarm->alarm_info;


	my $subject = $alarm->props->{subj} || 'alarm';

	my $mail = Email::Send->new({
			mailer => 'SMTP',
			mailer_args => [ Host => $self->host ]
		});

#	$subject = encode('cp1251', decode('utf8', $subject));
#	$message = encode('cp1251', decode('utf8', $message));
	foreach my $rec ( $alarm->get_recipients ) {
		my $msg = MIME::Lite->new(
			From => 'alarms@mtt.ru',
			To => $rec,
			Type => 'text/html; charset=UTF-8',
			Subject => $subject, #encode('MIME-B', $subject),
			Data => $message #encode('MIME-B', $message)
		);

		if ( $alarm->props->{attachment} eq 'html' || !$alarm->props->{attachment} ) {
			my $part = MIME::Lite->new(
				Type => 'text/html',
				Data => '<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"></head><body>' . $result . '</body></html>',
				Disposition => 'inline',
				Filename => 'alarm' . $alarm->id . '.html'
			);
			$part->attr('content-type.charset' => 'UTF-8');

			$msg->attach($part);
		}
		elsif ( $alarm->props->{attachment} eq 'csv' ) {
			my $part = MIME::Lite->new(
				Type => 'text/csv',
				Disposition => 'attachment',
				Data => $result,
				Filename => 'alarm' . $alarm->id . '.csv'
			);
			$part->attr('content-type.charset' => 'UTF-8');

			$msg->attach($part);
		}
		elsif ( $alarm->props->{attachment} eq 'excel' ) {
			my $part = MIME::Lite->new(
				Type => 'application/excel',
				Disposition => 'attachment',
				Data => $result,
				Filename => 'alarm' . $alarm->id . '.xls'
			);
			$part->attr('content-type.charset' => 'UTF-8');

			$msg->attach($part);
		}

		my $return = $mail->send( $msg->as_string() );
		warn "$return" if ! $return;
	}
}

__PACKAGE__->meta->make_immutable;
1;
